package amazon

import (
	"black_mamba/global"
	"black_mamba/pages"
	"black_mamba/workers"
	"database/sql"
	_ "embed"
	"fmt"
	"gitee.com/wengo/windows_gui/widget"
	"gitee.com/wengo/windows_gui/xc"
	"strconv"
	"sync"
	"time"
	"unsafe"
)

type CrawlerPage struct {
	pages.Foundation
	style        map[string]int
	taskTotal    *widget.ShapeText
	detailLayout *widget.LayoutEle
}

func NewCrawlerPage() *CrawlerPage {
	crawlerPage := &CrawlerPage{
		Foundation: pages.Foundation{
			ExecuteBtn: widget.NewButtonByName("crawlerExecuteBtn"),
			LogEdit:    widget.NewEditByName("crawlerLogEdit"),
			Style:      nil,
			Topic:      "crawler",
			//ListBoxLayout: widget.NewLayoutEleByName("couponListBoxLayout"),
			//ParentLayout:  widget.NewLayoutEleByName("couponParentLayout"),
		},
	}

	// 绑定执行按钮事件
	crawlerPage.ExecuteBtn.Event_BnClick(crawlerPage.execute)

	// 设置log样式
	crawlerPage.SetEditStyle()

	//绑定所有订阅
	crawlerPage.Subscribes()

	global.BM_EVENTBUS.Publish("crawler:log", map[string]string{"status": "info", "content": "暂无任务需要执行, 暂停1分钟再请求"})

	return crawlerPage
}

/* 事件回调 */
func (b *CrawlerPage) execute(pbHandled *bool) int {
	*pbHandled = true

	if global.BM_CONFIG.Section("basic").Key("serialNumberCiphertext").Value() == "" {
		b.UpdateLog(int(uintptr(unsafe.Pointer(&(map[string]string{"status": "error", "content": "请先设置机器序列号"})))))
		return 0
	}

	if global.BM_CONFIG.Section("proxy").Key("username").Value() == "" {
		b.UpdateLog(int(uintptr(unsafe.Pointer(&(map[string]string{"status": "error", "content": "请先设置代理用户名"})))))
		return 0
	}

	if global.BM_CONFIG.Section("proxy").Key("password").Value() == "" {
		b.UpdateLog(int(uintptr(unsafe.Pointer(&(map[string]string{"status": "error", "content": "请先设置代理密码"})))))
		return 0
	}

	//重绘父
	b.ToggleBtn(int(uintptr(unsafe.Pointer(b.ExecuteBtn))))

	go func() {

		ticker := time.NewTicker(1 * time.Millisecond)

		db, err := sql.Open("mysql",
			"root:123456@tcp(127.0.0.1:3306)/amazon_brand")
		if err != nil {
			panic(err)
			return
		}
		defer db.Close()

		rows, err := db.Query(`SELECT asin From products`)
		defer rows.Close()
		var taskWg sync.WaitGroup

		for {
			<-ticker.C
			if global.BM_POOL.Running() < 10 {
				var asin string
				rows.Next()
				rows.Scan(&asin)
				crawlerWorker := workers.NewCrawlerWorker()
				global.BM_POOL.Submit(crawlerWorker.Decorator(crawlerWorker.Execute, map[string]interface{}{
					"asin": asin,
				}, &taskWg, nil))
			}
		}

		//crawlerWorker := workers.NewCrawlerWorker()
		//var taskWg sync.WaitGroup
		//
		//for {
		//	if global.BM_POOL.Running() < 1 {
		//		result := global.BM_API.GetAsin()
		//		listing := gjson.Get(result, "data.asin").String()
		//		parse, _ := url.Parse(listing)
		//		err := global.BM_POOL.Submit(crawlerWorker.Decorator(crawlerWorker.Execute, map[string]interface{}{
		//			"listing": parse.Path,
		//		}, &taskWg, nil))
		//		if err != nil {
		//			return
		//		}
		//	} else {
		//		time.Sleep(1 * time.Second)
		//	}
		//}
		//
		//taskWg.Wait()
	}()

	return 0
}

func (b *CrawlerPage) updateTaskTotal(data int) int {
	result := *(*map[string]int)(unsafe.Pointer(uintptr(data)))
	b.taskTotal.SetText(fmt.Sprintf("当前任务组总数为: %d, 任务总数为: %d", result["taskGroupTotal"], result["taskTotal"]))
	b.taskTotal.Redraw()
	widget.NewLayoutEleByHandle(b.taskTotal.GetParentEle()).AdjustLayout(0)
	widget.NewLayoutEleByHandle(b.taskTotal.GetParentEle()).Redraw(true)

	return 0
}

func (b *CrawlerPage) updateFeedBack(feedback int) int {
	data := *(*map[interface{}]uint)(unsafe.Pointer(uintptr(feedback)))
	count := b.ListBox.GetCount_AD()
	if count > 0 {
		for iitem := 0; iitem < count; iitem++ {
			asin := b.ListBox.GetItemText(iitem, 1)
			val, ok := data[asin]
			if ok {
				curTotal, _ := strconv.Atoi(b.ListBox.GetItemText(iitem, 1))
				curTotal += int(val)
				xc.XAdTable_SetItemText(b.HAdapter, iitem, 3, strconv.Itoa(curTotal))
			}

		}
	}

	b.RedrawListBoxLayout()

	return 0
}
